package com.itheima.controller;

import com.itheima.domain.Employee;
import com.itheima.groups.GroupA;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;
import java.util.List;

@Controller
public class EmployeeController {

    @RequestMapping(value = "/addemployee")
    // @Valid开启校验
    public String addEmployee(@Validated({GroupA.class}) Employee employee, Errors errors, Model model){
        // System.out.println("errors.hasErrors() = " + errors.hasErrors());
        if (errors.hasErrors()){
            List<FieldError> fieldErrors = errors.getFieldErrors();
            // 校验异常数量
            System.out.println("fieldErrors.size() = " + fieldErrors.size());
            for (FieldError error : fieldErrors) {
                System.out.println("error.getField() = " + error.getField());
                System.out.println("error.getDefaultMessage() = " + error.getDefaultMessage());
                System.out.println();

                // 消息返回页面
                model.addAttribute(error.getField(),error.getDefaultMessage());
            }
            return "addemployee.jsp";
        }
        return "success.jsp";
    }

}
